package com.video.zlc.audioplayer;

import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static android.content.ContentValues.TAG;

/**
 * Created by guoxw on 2017/10/31.
 * <!- 实现拍照,录像:  并保存图片，视频到本地></!->
 */

public class CameraUtils
//        implements Camera.AutoFocusCallback
{

    private MediaRecorder mediaRecorder;
    private Camera camera;
    /*** 标识当前是前摄像头还是后摄像头  back:0  front:1*/
    private int backOrFtont = 0;
    private SurfaceHolder.Callback callback;
    private Context context;
    private SurfaceView surfaceView;
    /***录制视频的videoSize*/
    private int height, width;
    /***photo的height ,width*/
    private int heightPhoto, widthPhoto;

    private CameraManager mCameraManager;

    public void create(SurfaceView surfaceView, Context context) {
        this.context = context;
        this.surfaceView = surfaceView;
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//        surfaceView.setKeepScreenOn(true);

        Log.e("CU===create", "===");

        callback = new SurfaceHolder.Callback() {
            public void surfaceCreated(SurfaceHolder holder) {
                Log.e("CU===surfaceCreated", "==="+backOrFtont);

                camera = Camera.open();



//                mCameraManager = CameraManager.get();
//                mCameraManager.openDriver(holder);
//                mCamera = mCameraManager.getCamera();
//                Point point = mCameraManager.getCameraResolution();
//                AtomicInteger width = new AtomicInteger(point.y);
//                AtomicInteger height = new AtomicInteger(point.x);
//                int cropWidth = scanCropView.getWidth() * width.get() / scanContainer.getWidth();
//                int cropHeight = scanCropView.getHeight() * height.get() / scanContainer.getHeight();
//                setCropWidth(cropWidth);
//                setCropHeight(cropHeight);


                getVideoSize();


//                focus();

                mediaRecorder = new MediaRecorder();

//                backOrFtont = 0;
            }

            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.e("CU===surfaceChanged", "==="+backOrFtont);

//                doChange(holder);


//                setCamera();


                focus();

//                camera.stopPreview();
//                camera.release();
//                camera = null;
//                camera = Camera.open();
                try {
                    camera.setPreviewDisplay(surfaceView.getHolder());
                    camera.setDisplayOrientation(90);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                camera.startPreview();


            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.e("CU===surfaceDestroyed", "===");

                if (camera != null) {
                    camera.release();
                    camera = null;
                }
            }
        };
        surfaceView.getHolder().addCallback(callback);

    }

    private void doChange(SurfaceHolder holder) {
        try {
            focus();

            camera.setPreviewDisplay(holder);
            camera.setDisplayOrientation(90);
            camera.startPreview();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 切换摄像头
     */
    public void setCamera() {
        int cameraCount = 0;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);

            Log.e("setCamera===", backOrFtont+"===");

            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT && backOrFtont == 1) {
                camera.stopPreview();
                camera.release();
                camera = null;
                camera = Camera.open(i);
                try {
                    camera.setPreviewDisplay(surfaceView.getHolder());
                    camera.setDisplayOrientation(90);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                backOrFtont = 1;
                camera.startPreview();

                Log.e("setCamera===1", backOrFtont+"===");

                break;
            } else if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK && backOrFtont == 0) {
                camera.stopPreview();
                camera.release();
                camera = null;
                camera = Camera.open(i);
                try {
                    camera.setPreviewDisplay(surfaceView.getHolder());
                    camera.setDisplayOrientation(90);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                camera.startPreview();
                backOrFtont = 0;

                Log.e("setCamera===2", backOrFtont+"===");

                break;
            }
        }

    }

    /**
     * 切换摄像头
     */
    public void changeCamera() {
        int cameraCount = 0;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);

            Log.e("changeCamera===", backOrFtont+"===");

            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT && backOrFtont == 0) {
                camera.stopPreview();
                camera.release();
                camera = null;
                camera = Camera.open(i);

                focus();

                try {
                    camera.setPreviewDisplay(surfaceView.getHolder());
                    camera.setDisplayOrientation(90);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                backOrFtont = 1;
                camera.startPreview();

//

                Log.e("changeCamera===1", backOrFtont+"===");

                break;
            } else if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK && backOrFtont == 1) {
                camera.stopPreview();
                camera.release();
                camera = null;
                camera = Camera.open(i);

                focus();

                try {
                    camera.setPreviewDisplay(surfaceView.getHolder());
                    camera.setDisplayOrientation(90);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                camera.startPreview();
                backOrFtont = 0;

//                focus();

                Log.e("changeCamera===2", backOrFtont+"===");

                break;
            }
        }

//        focus();
    }

    public void stopRecord() {
        mediaRecorder.release();
        camera.release();
        mediaRecorder = null;
        camera = Camera.open();
        mediaRecorder = new MediaRecorder();
        doChange(surfaceView.getHolder());

//        camera.stopPreview();
//        camera.release();
//        camera = null;
//        camera = Camera.open();
//        try {
//            camera.setPreviewDisplay(surfaceView.getHolder());
//            camera.setDisplayOrientation(90);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
////        backOrFtont = 1;
//        camera.startPreview();
    }


    public void stop() {
        Log.e("CU===stop", "===");

//        if (mediaRecorder != null && camera != null) {
//            mediaRecorder.release();
//            camera.release();
//        }
    }

    public void destroy() {
        Log.e("CU===destroy", "===");

        if (mediaRecorder != null && camera != null) {
            mediaRecorder.release();
            camera.release();
            mediaRecorder = null;
            camera = null;
        }

    }

    /**
     * @param path 保存的路径
     * @param name 录像视频名称(不包含后缀)
     */
    public void startRecord(String path, String name) {
        camera.unlock();
        mediaRecorder.setCamera(camera);
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        //mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
//        mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());

//        CamcorderProfile profile;
//        profile.fileFormat=MediaRecorder.OutputFormat.MPEG_4;
//        profile.audioCodec=MediaRecorder.AudioEncoder.AAC;
//        profile.videoCodec=MediaRecorder.VideoEncoder.H264;
//        profile.videoBitRate= VideoMakerConfig.VIDEO_BIT;
//        profile.audioBitRate= VideoMakerConfig.AUDIO_BIT;
//
//        mediaRecorder.setProfile(profile);

//        mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
//        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);// 视频源
//        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);// 音频源率，然后就清晰了
//        mediaRecorder.setVideoEncodingBitRate(5*1024*1024);
//        mediaRecorder.setOrientationHint(90);// 输出旋转90度，保持竖屏录制
//        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);// 视频输出格式
//        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);// 音频格式
//        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);// 视频录制格式
//        // 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
//        mediaRecorder.setVideoSize(320, 240);
//        // 设置录制的视频帧率。必须放在设置编码和格式的后面，否则报错
//        mediaRecorder.setVideoFrameRate(10);


//
////        CamcorderProfile cProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
////        mediaRecorder.setProfile(cProfile);
////        mediaRecorder.setVideoFrameRate(30);
//
//        //设置文件输出格式
//        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
//        //设置音频编码方式
//        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
//        //设置视频编码方式
//        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);




        if(backOrFtont==0){
//            CamcorderProfile profile;
//            if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_QVGA)){
//                profile =CamcorderProfile.get(CamcorderProfile.QUALITY_QVGA);
//            }else {
//                profile =CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
//            }

            CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            mediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
//         设置录制的视频帧率。必须放在设置编码和格式的后面，否则报错
            mediaRecorder.setVideoFrameRate(30);
            mediaRecorder.setVideoEncodingBitRate(3000000);
        }



//        surfaceView.getHolder().setFixedSize(640,480);//最高只能设置640x480
//        mediaRecorder.setVideoSize(640,480);//最高只能设置640x480
//        //设置视频的最大持续时间
//        mediaRecorder.setMaxDuration(30000);

//        camera.autoFocus(this);
//        camera.getParameters().setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);

//        mediaRecorder.setVideoEncodingBitRate(700 * 1024);
//        mediaRecorder.setVideoSize(width, height);
//        mediaRecorder.setVideoFrameRate(24);
        //getVideoSize();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        Log.e("CU===", backOrFtont+"==="+path + File.separator + name + ".mp4");

        mediaRecorder.setOutputFile(path + File.separator + name + ".mp4");
        File file1 = new File(path + File.separator + name + ".mp4");
        if (file1.exists()) {
            file1.delete();
        }
        mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
        /***不设置时，录制的视频总是倒着，翻屏导致视频上下翻滚*/
        mediaRecorder.setOrientationHint(0);

//        surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);

        try {
            mediaRecorder.prepare();
            mediaRecorder.start();

//            camera.autoFocus(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 获取SupportedVideoSizes 控制输出视频width在300到600之间(尽可能小)
     * 获取PictureSize的大小(控制在w：1000-2000之间)
     */
    public void getVideoSize() {
        Camera.Parameters parameters = camera.getParameters();
        List<Camera.Size> videoSize = parameters.getSupportedVideoSizes();
        for (int i = 0; i < videoSize.size(); i++) {
            int width1 = videoSize.get(i).width;
            int height1 = videoSize.get(i).height;
            if (width1 >= 300 && width1 <= 600) {
                if (height1 >= 200 && height1 <= 600) {
                    width = width1;
                    height = height1;
                }

            }
            Log.d(TAG, "getVideoSize:----w:-- " + videoSize.get(i).width + "---h:--" + videoSize.get(i).height);
        }
        List<Camera.Size> photoSize = parameters.getSupportedPictureSizes();
        for (int i = 0; i < photoSize.size(); i++) {
            int width1 = photoSize.get(i).width;
            int height1 = photoSize.get(i).height;
            if (width1 >= 1000 && width1 <= 2000) {
                if (height1 >= 600 && height1 <=2000) {
                    widthPhoto = width1;
                    heightPhoto = height1;
                }

            }
        }

    }


    public void takePicture(String photoPath, String photoName) {

        camera.takePicture(null, null, new PictureCallBack(photoPath, photoName));

        Log.e("takePicture===", "===");

//        camera.autoFocus(this);
    }

    /**
     * 聚焦
     */
    public void focus(){
        Camera.Parameters parameters=camera.getParameters();

        Log.e("focus===", parameters.isSmoothZoomSupported()+"==="+parameters.isZoomSupported()+"==="+widthPhoto+"==="+heightPhoto);

        parameters.setPictureSize(widthPhoto,heightPhoto);
//        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
////        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
//        camera.setParameters(parameters);
//        camera.cancelAutoFocus();

        //自动对焦
//        List<String> focusMode=parameters.getSupportedFocusModes();
//        if (focusMode.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)){
//
//            Log.e("focus===2", parameters.isSmoothZoomSupported()+"==="+parameters.isZoomSupported());
//
//            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
//            camera.setParameters(parameters);
//            camera.cancelAutoFocus();
//        }

        List<String> focusMode=parameters.getSupportedFocusModes();
        if (focusMode.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)){

            Log.e("focus===2", parameters.isSmoothZoomSupported()+"==="+parameters.isZoomSupported());

            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            camera.setParameters(parameters);
            camera.cancelAutoFocus();
        }

//        camera.autoFocus(null);
    }

//    @Override
//    public void onAutoFocus(boolean success, Camera camera) {
//        if (success) {
//            Log.e(">>>>>>>>success", "==="+camera);
//        }else{
//            camera.autoFocus(this);//如果失败，自动聚焦
//        }
//    }

    /*** 拍照功能*/
    private class PictureCallBack implements Camera.PictureCallback {
        /*** 照片保存的路径和名称*/
        private String path;
        private String name;

        public PictureCallBack(String path, String name) {
            this.path = path;
            this.name = name;
        }

        @Override
        public void onPictureTaken(byte[] bytes, Camera camera) {
            File file1 = new File(path);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            File file = new File(path, name);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                try {
                    fos.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            camera.startPreview();


        }
    }
}
